import pymysql

#新建数据库工具类
class DBUtil(object):
    @classmethod
    def create_conn(cls):
       myconn = pymysql.connect(host="211.103.136.244", port=7061, user="student", password="iHRM_student_2022",
                                database="ihrm", charset='utf8')
       return myconn

   #封装查询数据的方法
    @classmethod
    def query_one(cls,sql):
        mycuror=None
        myconn=None
        data=None
        try:
            # 创建连接
            # myconn = pymysql.connect(host="211.103.136.244", port=7061, user="student", password="iHRM_student_2022",
            #                          database="test_db", charset='utf8')
            myconn=DBUtil.create_conn()
            # 获取游标
            mycuror = myconn.cursor()
            # 执行sql语句
            mycuror.execute(sql)
            # 获取结果集里面的数据
            data = mycuror.fetchone()
        except Exception as e:
            print("查询异常：",str(e))
        finally:
            # 关闭 游标
            mycuror.close()
            # 关闭连接
            myconn.close()
            return data
    @classmethod
    def db_uid(cls,sql):
        myconn=None
        mycursor=None
        try:
            # 创建连接
            # myconn = pymysql.connect(host="211.103.136.244", port=7061, user="student", password="iHRM_student_2022",
            #                          database="test_db", charset='utf8')
            myconn = DBUtil.create_conn()
            # 创建游标
            mycursor = myconn.cursor()
            # 执行sql语句
            mycursor.execute(sql)
            # 提交事务
            myconn.commit()
        except Exception as e:
            print("增删改异常为:",str(e))
            myconn.rollback()
        finally:
            mycursor.close()
            # 关闭连接
            myconn.close()
